package com.wanghaoran.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanghaoran.dto.PageDTO;
import com.wanghaoran.dto.RoomInsertDTO;
import com.wanghaoran.dto.RoomPageDTO;
import com.wanghaoran.dto.RoomUpdateDTO;
import com.wanghaoran.entity.Room;
import com.wanghaoran.excel.RoomExcel;
import com.wanghaoran.exception.IllegalParamException;
import com.wanghaoran.exception.ServerErrorException;
import com.wanghaoran.exception.VersionException;
import com.wanghaoran.mapper.RoomMapper;
import com.wanghaoran.service.RoomService;
import com.wanghaoran.vo.RoomVO;
import jakarta.annotation.Resource;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLongHexNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wanghaoran
 */
@Service
@CacheConfig(cacheNames = "room")
public class RoomServiceImpl implements RoomService {

    @Resource
    private RoomMapper roomMapper;

    @CacheEvict(allEntries = true)
    @Override
    public int insert(RoomInsertDTO dto) {
        Room room = BeanUtil.copyProperties(dto, Room.class);
        // 设置默认值
        if(StrUtil.isBlank(dto.getInfo())) {
            room.setInfo("暂无描述");
        }
        room.setVersion(0L);
        room.setDeleted(0);
        room.setCreated(LocalDateTime.now());
        room.setUpdated(LocalDateTime.now());
        // DB添加
        int result = roomMapper.insert(room);
        if (result < 0) {
            throw new ServerErrorException("DB添加失败");
        }
        return result;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Room select(Long id) {
        // DB查询
        Room result = roomMapper.select(id);
        if(ObjectUtil.isNull(result)) {
            throw new ServerErrorException("ID不存在");
        }
        return result;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<RoomVO> list() {
        return roomMapper.list(new RoomPageDTO())
                .stream()
                .map(room -> BeanUtil.copyProperties(room, RoomVO.class))
                .collect(Collectors.toList());
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
                condition = "#p0 != null",
                unless = "#result == null")
    @Override
    public PageInfo<Room> page(RoomPageDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo<>(roomMapper.list(dto));
    }

    @CacheEvict(allEntries = true)
    @Transactional
    @Retryable(retryFor = VersionException.class)
    @Override
    public int update(RoomUpdateDTO dto) {
        Long id = dto.getId();
        if(ObjectUtil.isNull(id)){
            throw new IllegalParamException("ID为空");
        }
        Room room = roomMapper.select(id);
        if(ObjectUtil.isNull(room)){
            throw new ServerErrorException("记录不存在");
        }
        BeanUtil.copyProperties(dto, room);
        // 设置默认值
        room.setUpdated(LocalDateTime.now());
        //  DB修改
        int result = roomMapper.update(room);
        if (result <= 0) {
            throw new VersionException("DB修改失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int delete(Long id) {
        int result = roomMapper.delete(id);
        if (result <= 0) {
            throw new ServerErrorException("DB删除失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteBatch(List<Long> ids) {
        int result = roomMapper.deleteBatch(ids);
        if (result <= 0) {
            throw new ServerErrorException("DB批量删除失败");
        }
        return result;
    }

    @Override
    public List<RoomExcel> getExcelData() {
         return roomMapper.list(new RoomPageDTO())
                .stream()
                .map(room -> BeanUtil.copyProperties(room, RoomExcel.class))
                .collect(Collectors.toList());
    }
}
